﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace WebApplication1
{
    public partial class WebForm5 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Marka.Text = Request.QueryString["Marka"];
            Model.Text = Request.QueryString["Model"];
            Page.Title = Marka.Text + " " + Model.Text + " - Информации";
            GalerijaButton.ToolTip = "Галерија за моделот " + Marka.Text + " " + Model.Text;
            INFOHyperLink.ToolTip = "Официјална web страна за " + Marka.Text + " " + Model.Text;
            lblOcena.Text = "Оценете го моделот " + Marka.Text + " " + Model.Text + ": ";
            lblKomentar.Text = "Оставете коментар за моделот " + Marka.Text + " " + Model.Text + ": ";
            btnOceni.ToolTip = "Оценете го " + Marka.Text + " " + Model.Text;

            MetaFbTitle.Visible = MetaFbImage.Visible = MetaFbDescription.Visible = true;
            
            MetaFbTitle.Text = "<meta property=\"og:title\" content=\"" + Marka.Text + " " + Model.Text + "\" />";
            MetaFbDescription.Text = "<meta property=\"og:description\" content=\"Информации за моделот " + Marka.Text + " " + Model.Text + "\" />";
            MetaFbImage.Text = "<meta property=\"og:image\" content=\"Sliki\\FB-Thumbnails\\" + Marka.Text + "\\" + Marka.Text + " " + Model.Text + ".jpg\" />";

            string tekovnoUrl = HttpContext.Current.Request.Url.AbsoluteUri;
            string promenetoUrl = tekovnoUrl.Replace("&", "%26").Replace(" ", "%20");

            FacebookShareLink.NavigateUrl = "http://www.facebook.com/sharer.php?u=" + promenetoUrl + "&t=" + Marka.Text + " " + Model.Text;
            TwitterShareLink.NavigateUrl = "http://twitter.com/share?url=" + promenetoUrl;

            if (!IsPostBack)
            {
                LoadData(Model.Text);
                MotoriListBox.SelectedIndex = 0;

                for (int i = 10; i >= 1; i--)
                    ddlOcena.Items.Add((i).ToString());
            }
            izberiMotor(MotoriListBox.SelectedValue);

            LoadOcena(Model.Text);
        }

        protected void LoadData(string Mod)
        {
            MotoriListBox.Items.Clear();

            MySqlConnection konekcija = new MySqlConnection();
            konekcija.ConnectionString = ConfigurationManager.ConnectionStrings["MojaKonekcija"].ConnectionString;
            // konekcija.ConnectionString = "server=localhost;User Id=root;database=avtomobili;";

            MySqlCommand komanda = new MySqlCommand();
            komanda.Connection = konekcija;
            komanda.CommandText = "SELECT * FROM motori WHERE Model='" + Mod + "'"; //"SELECT * FROM modeli MODEL, motori MOTOR, proizvoditeli PROIZ WHERE MODEL.Model='" + Mod + "' AND MODEL.Model=MOTOR.Model AND MODEL.Proizvoditel=PROIZ.ImeProizvoditel ORDER BY MOTOR.Gorivo, MOTOR.Motor";

            try
            {
                konekcija.Open();

                MySqlDataReader citac = komanda.ExecuteReader();
                while (citac.Read())
                {
                    ListItem element = new ListItem();
                    element.Text = citac["Motor"].ToString() + " - " + citac["SilaKS"].ToString() + " KS";
                    element.Value = citac["Broj"].ToString();
                    MotoriListBox.Items.Add(element);
                }
                citac.Close();
            }
            catch (Exception ex)
            {
                //  Label2.Text = ex.Message;
            }
            finally
            {
                konekcija.Close();
            }
        }

        protected void GalerijaButtonClick(object sender, EventArgs e)
        {
            Response.Redirect("Galerija.aspx?Marka=" + Marka.Text + "&Model=" + Model.Text);
        }

        protected void MotoriListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            izberiMotor(MotoriListBox.SelectedItem.Value);
        }

        protected void izberiMotor(string ID)
        {
            MySqlConnection konekcija = new MySqlConnection();
            konekcija.ConnectionString = ConfigurationManager.ConnectionStrings["MojaKonekcija"].ConnectionString;
            // konekcija.ConnectionString = "server=localhost;User Id=root;database=avtomobili;";

            MySqlCommand komanda = new MySqlCommand();
            komanda.Connection = konekcija;
            komanda.CommandText = "SELECT * FROM modeli MODEL, motori MOTOR, proizvoditeli PROIZ WHERE MOTOR.Broj='" + ID + "' AND MOTOR.Model=MODEL.Model AND MODEL.Proizvoditel=PROIZ.ImeProizvoditel ORDER BY MOTOR.Gorivo, MOTOR.Motor";

            try
            {
                konekcija.Open();

                MySqlDataReader citac = komanda.ExecuteReader();
                if (citac.Read())
                {
                    MarkaLabel.Text = citac["Proizvoditel"].ToString();
                    ModelLabel.Text = citac["Model"].ToString();
                    MotorLabel.Text = citac["Motor"].ToString();
                    GorivoLabel.Text = citac["Gorivo"].ToString();
                    SilaLabel.Text = citac["SilaKS"].ToString() + " KS";
                    ZafatninaLabel.Text = citac["Zafatnina"].ToString() + " ccm";
                    PotrosuvackaLabel.Text = citac["Potrosuvacka"].ToString() + " l/100km";
                    CenaLabel.Text = citac["CenaEvra"].ToString() + " €";
                    ModelOpis.Text = citac["Informacii"].ToString();
                    INFOHyperLink.Text = citac["WebProizvoditeli"].ToString();
                    INFOHyperLink.NavigateUrl = citac["WebModeli"].ToString();
                    INFOHyperLink.Target = "_blank";
                    INFOHyperLink.ToolTip = "Официјална web страна за " + Marka.Text + " " + Model.Text;
                    SlikaINFO.ImageUrl = "Sliki/" + MarkaLabel.Text + "/320x240/" + citac["Slika"].ToString();
                }
                citac.Close();
            }
            catch (Exception ex)
            {
                //  Label2.Text = ex.Message;
            }
            finally
            {
                konekcija.Close();
            }
        }

        protected void LoadOcena(string Mod)
        {
            MySqlConnection konekcija = new MySqlConnection();
            konekcija.ConnectionString = ConfigurationManager.ConnectionStrings["MojaKonekcija"].ConnectionString;
            // konekcija.ConnectionString = "server=localhost;User Id=root;database=avtomobili;";

            MySqlCommand komanda = new MySqlCommand();
            komanda.Connection = konekcija;
            komanda.CommandText = "SELECT * FROM oceni WHERE Model='" + Mod + "'";

            try
            {
                konekcija.Open();

                MySqlDataReader citac = komanda.ExecuteReader();
                if (citac.Read())
                {
                    lblZbirGlasovi.Text = citac["ZbirGlasovi"].ToString();
                    lblBrojGlasanja.Text = citac["BrojGlasanja"].ToString();
                    lblSrednaOcena.Text = "Средна оцена: " + (Convert.ToDouble(citac["ZbirGlasovi"]) / Convert.ToInt32(citac["BrojGlasanja"])).ToString() + " од вкупно " + citac["BrojGlasanja"];
                    if (Convert.ToInt32(citac["BrojGlasanja"]) == 1)
                        lblSrednaOcena.Text += " гласање";
                    else
                        lblSrednaOcena.Text += " гласања";
                }
                citac.Close();
            }
            catch (Exception ex)
            {
                //  Label2.Text = ex.Message;
            }
            finally
            {
                konekcija.Close();
            }
        }

        protected void PorackaButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("Poracka.aspx?Marka=" + Marka.Text + "&Model=" + Model.Text + "&Motor=" + MotoriListBox.SelectedValue);
        }

        protected void btnOceni_Click(object sender, EventArgs e)
        {
            Oceni(lblSrednaOcena.Text);
            LoadOcena(Model.Text);
        }

        public bool Oceni(String sredna)
        {
            MySqlConnection con = new MySqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["MojaKonekcija"].ConnectionString;
            // MySqlConnection con = new MySqlConnection("server=localhost;User Id=root;database=avtomobili;password=ace;");
            string komanda;
            MySqlCommand cmd = new MySqlCommand();
            if (lblSrednaOcena.Text == "")
            {
                komanda = "INSERT INTO oceni(Model, BrojGlasanja, ZbirGlasovi) VALUES(@Model,@BrojGlasanja,@ZbirGlasovi)";
                
                cmd = new MySqlCommand(komanda, con);
                cmd.Parameters.AddWithValue("@Model", Model.Text);
                cmd.Parameters.AddWithValue("@BrojGlasanja", (1).ToString());
                cmd.Parameters.AddWithValue("@ZbirGlasovi", ddlOcena.SelectedValue);
            }
            else
            {
                komanda = "UPDATE oceni SET BrojGlasanja=@BrojGlasanja, ZbirGlasovi=@ZbirGlasovi WHERE Model=@Model";

                cmd = new MySqlCommand(komanda, con);
                cmd.Parameters.AddWithValue("@ZbirGlasovi", (Convert.ToInt32(lblZbirGlasovi.Text) + Convert.ToInt32(ddlOcena.SelectedValue)).ToString());
                cmd.Parameters.AddWithValue("@BrojGlasanja", (Convert.ToInt32(lblBrojGlasanja.Text) + 1).ToString());
                cmd.Parameters.AddWithValue("@Model", Model.Text);
            }

            MySqlDataReader rd = null;

            try
            {
                con.Open();
                rd = cmd.ExecuteReader();
                rd.Close();
            }
            catch (MySqlException ex)
            {
                //   MessageBox.Show(ex.Message);
                return false;
            }
            finally
            {
                con.Close();
            }
            return true;
        }

        protected void btnKomentar_Click(object sender, EventArgs e)
        {
            if ((txtKomentar.Text != "") && (txtOdKogo.Text != ""))
            {
                if (VnesiKomentar(Model.Text, txtKomentar.Text, txtOdKogo.Text))
                  lblStatus.Text = "Коментарот е внесен!";
                else
                  lblStatus.Text = "Коментарот НЕ Е внесен!";

                txtKomentar.Text = "";
                txtOdKogo.Text = "";
            }
            else
            {
                lblStatus.Text = "Морате да внесете коментар и име!";
            }
        }

        public bool VnesiKomentar(String Model, String Komentar, String OdKogo)
        {
            MySqlConnection con = new MySqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["MojaKonekcija"].ConnectionString;
            // MySqlConnection con = new MySqlConnection("server=localhost;User Id=root;database=avtomobili;password=ace;");
            MySqlCommand cmd = new MySqlCommand("INSERT INTO komentari(Model, Komentar, OdKogo, Odobreno) VALUES(@Model,@Komentar,@OdKogo,0)", con);

            cmd.Parameters.AddWithValue("@Model", Model);
            cmd.Parameters.AddWithValue("@Komentar", Komentar);
            cmd.Parameters.AddWithValue("@OdKogo", OdKogo);

            MySqlDataReader rd = null;

            try
            {
                con.Open();
                rd = cmd.ExecuteReader();
                rd.Close();
            }
            catch (MySqlException ex)
            {
                //   MessageBox.Show(ex.Message);
                return false;
            }
            finally
            {
                con.Close();
            }
            return true;
        }
    }
}
